package translate

import (
	"cmd-tools/utils"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
	"net/url"
	"regexp"
)

var (
	AppId  = "xxxxx"
	AppKey = "xxxxx"
	AppUrl = "https://fanyi-api.baidu.com/api/trans/vip/translate"
)

type TransResult struct {
	Src string `json:"src"`
	Dst string `json:"dst"`
}

type TransEnd struct {
	From        string        `json:"from"`
	To          string        `json:"to"`
	TransResult []TransResult `json:"trans_result"`
}

// Translation 翻译
type Translation struct {
	languages string // 语言
	target    string // 目标
}

func NewTranslation() *Translation {
	return &Translation{}
}

func (t *Translation) Do(target string) (string, error) {
	// 判断是否包含中文，包含的话，就是翻译为英文
	match, _ := regexp.Match("[\u4e00-\u9fa5]", []byte(target))
	if match {
		t.languages = "en"
	} else {
		t.languages = "zh"
	}

	salt := utils.CreateRandom()
	params := make(url.Values)
	params["q"] = []string{target}
	params["from"] = []string{"auto"}
	params["to"] = []string{t.languages}
	params["appid"] = []string{AppId}
	params["salt"] = []string{salt}
	params["sign"] = []string{utils.Med5EncryptionWithSalt(AppId, target, salt, AppKey)}
	response, err := http.PostForm(AppUrl, params)
	if err != nil {
		return "", err
	}
	if response.StatusCode == http.StatusOK {
		result := TransEnd{}
		bytes, _ := ioutil.ReadAll(response.Body)
		json.Unmarshal(bytes, &result)
		return result.TransResult[0].Dst, nil
	}
	return "", errors.New("请求失败")
}
